package com.xjcs.saplingplan.adapter

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

class RecyclerViewItemDecoration(
    context: Context,
    private val dividerHeight: Int = 1, // dp
    private val dividerColor: Int = Color.GRAY
) : RecyclerView.ItemDecoration() {

    private val paint: Paint
    private val dividerHeightPx: Int

    init {
        val metrics = context.resources.displayMetrics
        dividerHeightPx = (dividerHeight * metrics.density).toInt()

        paint = Paint().apply {
            this.color = dividerColor
            this.style = Paint.Style.FILL
        }
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        if (parent.layoutManager == null) return

        val layoutManager = parent.layoutManager!!

        for (i in 0 until parent.childCount) {
            val child = parent.getChildAt(i)
            val position = parent.getChildAdapterPosition(child)

            // 不在最后一项下方绘制分割线（可根据需求调整）
            if (position == RecyclerView.NO_POSITION || position == parent.adapter?.itemCount?.minus(
                    1
                )
            ) {
                continue
            }

            val params = child.layoutParams as RecyclerView.LayoutParams

            val top: Int
            val bottom: Int
            val left: Int
            val right: Int

            if (layoutManager.canScrollVertically()) { // 垂直列表
                top = child.bottom + params.bottomMargin
                bottom = top + dividerHeightPx
                left = parent.paddingLeft
                right = parent.width - parent.paddingRight
            } else { // 水平列表（你自己根据需求实现）
                left = child.right + params.rightMargin
                right = left + dividerHeightPx
                top = parent.paddingTop
                bottom = parent.height - parent.paddingBottom
            }

            c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint)
        }
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val position = parent.getChildAdapterPosition(view)
        val itemCount = parent.adapter?.itemCount ?: 0

        // 一般只在非最后一项下方添加 offset
        if (position != RecyclerView.NO_POSITION && position < itemCount - 1) {
            if (parent.layoutManager?.canScrollVertically() == true) {
                outRect.bottom = dividerHeightPx
            } else {
                outRect.right = dividerHeightPx
            }
        } else {
            outRect.setEmpty()
        }
    }
}